const app = getApp();
const s = new app.Shuju();
var nandu = 0;
var lastcid = 0;
const recorderManager = wx.getRecorderManager();
var luyin = false;
var timer = null;
var nandu = "";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    baseimg: app.baseimg,
    swiperList: [],
    word: {},
    words: [],
    show:false
  },

  _Bofang: function () {
    let text = this.data.word.zi;
    app.baidutoken().then((token) => {
      const innerAudioContext = wx.createInnerAudioContext({
        useWebAudioImplement: false
      })
      innerAudioContext.src = "http://tsn.baidu.com/text2audio?lan=zh&ctp=1&cuid=abcdxxx&tok=" + token + "&tex=" + text + "&vol=9&per=0&spd=5&pit=5&aue=3"
      innerAudioContext.play();
    })
  },

  _Langdu: function (e) {
    let text = e.currentTarget.dataset.for;
    app.baidutoken().then((token) => {
      const innerAudioContext = wx.createInnerAudioContext({
        useWebAudioImplement: false
      })
      innerAudioContext.src = "http://tsn.baidu.com/text2audio?lan=zh&ctp=1&cuid=abcdxxx&tok=" + token + "&tex=" + text + "&vol=9&per=0&spd=5&pit=5&aue=3"
      innerAudioContext.play();
    })
  },

  _Getallwords: function () {
    return new Promise((succ, err) => {
      s.sb("wenzi");
      s.se("tj","nandu");
      s.se("nandu",nandu);
      s.g("c/common_list", {
        s: (d) => {
          if (d.code == 200) {
            this.setData({
              words: d.data
            })
            succ();
          }
        }
      })
    })
  },

  //获取我当前的进度
  _Getjindu: function () {
    return new Promise((succ, err) => {
      s.sb("xuexi");
      s.si("uid");
      s.se("tj", "uid");
      s.se("limit", 1);
      s.se("order", "id");
      s.g("c/common_list", {
        s: (d) => {
          if (d.code == 200) {
            let list = d.data;
            if (list.length > 0) {
              lastcid = list[0].cid; //即上一次学的这个wid
            } else {
              lastcid = 0;
            }
            succ();
          }
        }
      })
    })
  },

  //获取现在应该学的单词
  _Getdanci: function () {
    return new Promise((succ, err) => {
      if (lastcid == 0) {
        //第一个单词
        this.setData({
          word: this.data.words[0]
        })
      } else {
        //先获取上一个单词在数组中的位置
        let all = this.data.words;
        let idx = 0;
        for (let i = 0; i < all.length; i++) {
          if (all[i].id == lastcid) {
            idx = i;
            break;
          }
        }
        //判断这个是不是最后一个
        if (idx == all.length - 1) {
          //那么最新的单词就是第一个
          this.setData({
            word: this.data.words[0]
          })
        } else {
          //否则就是下一个
          this.setData({
            word: this.data.words[idx + 1]
          })
        }
      }
      succ();
    })
  },

  _Getciyu: function () {
    return new Promise((succ, err) => {
      s.sb("ciyu");
      s.se("wid", this.data.word.id);
      s.se("tj", "wid");
      s.g("c/common_list", {
        s: (d) => {
          if (d.code == 200) {
            this.setData({
              swiperList: d.data
            })
            succ();
          }
        }
      })
    })
  },

  _Next: function () {
    lastcid = this.data.word.id;
    //当前的这个要记录
    s.si("uid");
    s.se("cid", lastcid);
    s.sb('xuexi');
    s.se('nandu',nandu);
    s.g("c/info_charu", {
      s: (d) => {
        if (d.code == 200) {
          this.setData({
            show:false
          })
          this._Getdanci().then(() => {
            return this._Getciyu();
          })    
        }
      }
    })
  },

  startRecording() {
    recorderManager.start({
      format: 'wav',
      sampleRate: 16000,
      numberOfChannels: 1,
      success: res => {
        console.log('开始录音', res);
      },
      fail: err => {
        console.error('录音失败', err);
      }
    });
    app.ts("开始录音");
  },

  StopLuyin:function(){
    recorderManager.stop();
  },

  // 停止录音并转换语音为文字  
  stopRecording(tempFilePath) {
    let that = this;
    // 将录音文件转换为文字  
    console.log(tempFilePath)
    app.baidutoken().then((token)=>{
      const fs = wx.getFileSystemManager();
      fs.readFile({//读取文件并转为ArrayBuffer
        filePath: tempFilePath,
        success(res) {
          const base64 = wx.arrayBufferToBase64(res.data);
          console.log(base64)
          var fileSize = res.data.byteLength;
          wx.request({
            url: 'https://vop.baidu.com/server_api',
            data: {
              format: 'wav',
              rate: 16000,
              channel: 1,
              cuid: 'sdfdfdfsfs',
              token: token,
              speech: base64,
              len: fileSize
            },
            method: 'POST',
            header: {
              'content-type': 'application/json' // 默认值
            },
            success(res) {
              wx.hideLoading();
              console.log(res.data);
              var result = res.data.result;
              if (result.length == 0){
                wx.showToast({
                  title: "未识别到语音信息!",
                  icon: 'none',
                  duration: 3000
                })
                return ;
              }
              var keyword = result[0];
              keyword = keyword.replace("。", "");
              console.log(keyword);
              app.ts(keyword)
              that._Chulires(keyword);
            }
          })
        }
      })
    })

  },

  _Chulires:function(text){
    if(text == this.data.word.zi){
      app.ts("读音正确");
      this.setData({
        show:true
      })
    }else{
      app.te("读音错误");
    }
  },

  _Getjindu:function(){
    return new Promise((succ,err)=>{
      s.si("uid");
      s.se("nandu",nandu);
      s.sb("xuexi");
      s.se("tj","uid,nandu");
      s.se("limit",1);
      s.se("order","id");
      s.g('c/common_list',{
        s:(d)=>{
          if(d.code == 200){
            let list = d.data;
            if(list.length > 0){
              lastcid = list[0].cid;
            }
            succ();
          }
        }
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let n = options.n || 0;
    nandu = ['入门','低','中','高'][n];
    this._Getallwords().then(()=>{
      return this._Getjindu();
    }).then(() => {
      return this._Getdanci()
    }).then(() => {
      return this._Getciyu();
    })

    timer = setInterval(() => {
      s.si("uid");
      s.se("day",app.Day().get());
      s.g("p/jilushichang",{
        s:(d)=>{
          if(d.code == 200){
            console.log("记录");
          }
        }
      })
    }, 1000*5);

    recorderManager.onStop((res) => {
      // 停止录音  
      this.stopRecording(res.tempFilePath);
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    // clearInterval(timer);
    // timer = null;
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    clearInterval(timer);
    timer = null;
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})